import modelExtend from 'dva-model-extend'
import {lwjPageModel} from 'utils/model'
import pathToRegexp from 'path-to-regexp'
import {routerRedux} from 'dva/router'
import {
  query,
  queryClassifyList,
  addToCart,
  queryCartCount
} from './services/salesmarket'
import { message } from 'antd'

export default modelExtend(lwjPageModel, {
  namespace: 'salesmarket',
  state: {
    classifyList: [],
    searchClassifyKeyword: '',
    classifyId: null,
    productList: [],
    queryParam: {},
    detailModal: false,
    detailUrl: '',
    count: 0,
    pagination: {},
    selectedDistributorId: '-1',
    pagination: {
        current: 1,
        total: 0,
        showTotal: total => `共 ${total} 条`,
        showSizeChanger: true,
        showQuickJumper: true,
        defaultPageSize: 10,
        pageSize: 10
    }
  },
  subscriptions: {
    setup({dispatch, history}) {
      history.listen(({pathname, search}) => {
        const match = pathToRegexp('/salesmarket/salesmarket').exec(pathname);
        let distributorIdMatch = search.match(/id=(.*)$/);
        if(match){
            dispatch({
              type: 'reset',
              selectedDistributorId: (distributorIdMatch && distributorIdMatch.length > 0 ? distributorIdMatch[1] : '-1')
            })
            dispatch({
              type: 'query',
              payload: {
                start: 0,
                limit: 10
              }
            })
            dispatch({
              type: 'queryClassifyList'
            })
            dispatch({
              type: 'queryCartCount'
            })
        }
      })
    }
  },
  effects: {
    * query({
        payload
    }, {call, put, select}) {
      let selectedDistributorId = yield select(({salesmarket}) => salesmarket.selectedDistributorId);
      if(!selectedDistributorId || (selectedDistributorId == '-1')){
        yield put({
            type: 'success',
            payload: {
              list: [],
              pagination: {
                  current: 1,
                  total: 0,
                  showTotal: total => `共 ${total} 条`,
                  showSizeChanger: true,
                  showQuickJumper: true,
                  defaultPageSize: 10,
                  pageSize: 10
              }
            }
        });
      }else{
        let classifyId = yield select(({salesmarket}) => salesmarket.classifyId);
        let queryParam = yield select(({salesmarket}) => salesmarket.queryParam);
        const {result: data} = yield call(query, { 
          start: payload.start,
          limit: payload.limit,
          cateIdAndChild: classifyId,
          name: queryParam.name,
          goods_id: queryParam.goods_id,
          id: queryParam.id,
          status: queryParam.status,
          sort: 'id',
          order: 'DESC',
          distributorId: (selectedDistributorId == '-1' ? null : selectedDistributorId)
        });
        yield put({
            type: 'success',
            payload: {
              list: data.content,
              pagination: {
                  current: payload.start + 1,
                  total: data.totalElements,
                  showTotal: total => `共 ${total} 条`,
                  showSizeChanger: true,
                  showQuickJumper: true,
                  defaultPageSize: 10,
                  pageSize: data.size
              }
            }
        });
      }
    },
    * queryClassifyList({}, {call, put, select}) {
        const {result: data} = yield call(queryClassifyList);
        yield put({
            type: 'setClassifyList',
            classifyList: data
        });
    },
    * queryCartCount({}, {call, put, select}) {
      let selectedDistributorId = yield select(({salesmarket}) => salesmarket.selectedDistributorId);
      if(!selectedDistributorId || (selectedDistributorId == '-1')){
        yield put({
          type: 'setCartCount',
          count: 0
        })
      }else{
        const {result} = yield call(queryCartCount, {
          distributorId: (selectedDistributorId == '-1' ? null : selectedDistributorId)
        });
        yield put({
          type: 'setCartCount',
          count: result
        })
      }
    },
    * addToCart({item}, {call, put, select}) {
      let selectedDistributorId = yield select(({salesmarket}) => salesmarket.selectedDistributorId);
      if(selectedDistributorId && (selectedDistributorId != '-1')){
        const {result} = yield call(addToCart, {
          commodityId: item.id,
          number: 1,
          distributorId: (selectedDistributorId == '-1' ? null : selectedDistributorId)
        });
        message.success("添加成功");
        yield put({
          type: 'setCartCount',
          count: result
        })
      }
    },
  },

  reducers: {
    success(state, {payload}) {
      return {
        ...state,
        productList: payload.list,
        pagination: payload.pagination
      }
    },
    //请求类目列表数据
    setClassifyList(state, {classifyList}) {
      return {
        ...state,
        classifyList
      }
    },
    //更新选中的类目id
    setClassifyId(state, {classifyId}) {
      return{
        ...state,
        classifyId
      }
    },
    //树结构搜索
    setClassifySearchKeyword(state, {keyword}) {
      return{
        ...state,
        searchClassifyKeyword: keyword
      }
    },
    //列表搜索
    setQueryParam(state, {queryParam}) {
      return{
        ...state,
        queryParam
      }
    },
    //显示详情弹窗
    showProductDetail(state, {detailUrl}) {
      return {
        ...state,
        detailModal:true,
        detailUrl:detailUrl
      }
    },
    //关闭详情弹窗
    hideProductDetail(state, {}) {
      return {
        ...state,
        detailModal:false,
        detailUrl:''
      }
    },
    //购物车数量
    setCartCount(state, {count}) {
      return {
        ...state,
        count
      }
    },
    changeDistributor (state, {selectedDistributorId}) {
      return {
        ...state,
        selectedDistributorId
      }
    },
    reset(state, {selectedDistributorId}) {
      return{
        ...state,
        selectedDistributorId,
        searchClassifyKeyword: '',
        classifyId: null,
        productList: [],
        queryParam: {},
        detailModal: false,
        detailUrl: '',
        count: 0,
        pagination: {},
      }
    }
  }
})
